<template>
  <div class="add-activity">
   <div class="box">
      <div class="screen">
      <span>开始时间:</span>
      <div class="screen-item">
        <el-date-picker
          v-model="start"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择开始时间"
          :disabled="!row.copy && (row.status == '1' || row.status == '2')"
        >
        </el-date-picker>
      </div>

      <span>结束时间:</span>
      <div class="screen-item">
        <el-date-picker
          v-model="end"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择结束时间"
          :disabled="!row.copy && (row.status == '1' || row.status == '2')"
        >
        </el-date-picker>
      </div>
    </div>
    <div class="tablebox" ref="tablebox">
      <el-table :data="list" :height="oHeight" style="width: 100%" :key="key">
      <el-table-column
        prop="pgoods_name"
        label="商品选择"
        width="350px"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button
            v-if="row.status == '-1' || row.status == '0'"
            type="primary"
            @click="editGoods(scope.row)"
            >选择</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="pgoods_storage" label="库存"> </el-table-column>
      <el-table-column prop="pgoods_price" label="售价(元)">
        <template slot-scope="scope">
          {{ scope.row.pgoods_points / 100 }}
        </template>
      </el-table-column>
      <el-table-column label="拼团价(元)">
        <template slot-scope="scope">
          <el-input
            :disabled="!row.copy && (row.status == '1' || row.status == '2')"
            v-model="scope.row.pt_price"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="成团人数">
        <template slot-scope="scope">
          <el-input
            :disabled="!row.copy && (row.status == '1' || row.status == '2')"
            v-model="scope.row.minimum_people"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="成团限时时间">
        <template slot-scope="scope">
          <el-select
            :disabled="!row.copy && (row.status == '1' || row.status == '2')"
            v-model="scope.row.expire_type"
          >
            <el-option
              v-for="t in timeList"
              :key="t.value"
              :value="t.value"
              :label="t.label"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="排序">
        <template slot-scope="scope">
          <el-input
            :disabled="!row.copy && (row.status == '1' || row.status == '2')"
            v-model="scope.row.sort"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button
            v-if="row.status == '-1' || row.status == '0' || row.copy"
            type="primary"
            @click="deleteGoods(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    </div>
    <div class="btnbox">
      <el-button
      v-if="row.status == '-1' || row.status == '0' || row.copy"
      class="add-commodity"
      type="primary"
      @click="submitCommodity"
      >提交</el-button
    >
    <el-button
      v-if="row.status == '-1' || row.status == '0' || row.copy"
      class="add-commodity"
      type="primary"
      @click="addCommodity"
      >新增</el-button
    >
    </div>
   </div>

    <!-- 新增商品弹出抽屉 -->
    <el-drawer
      title="商品选择"
      :visible.sync="drawerVibile"
      @close="closeDrawer"
      size="60%"
    >
      <div class="commodity-search">
        <span>商品名称:</span>
        <el-input v-model="searchObj.pgoods_name"></el-input>
        <span>商品ID:</span>
        <el-input v-model="searchObj.pgoods_id"></el-input>
        <el-button type="primary" @click="searchGoods">搜索</el-button>
      </div>
      <div class="commodity-table">
        <el-table
          :data="searchList"
          border
          :height="theight"
          style="width: 100%"
        >
          <el-table-column
            prop="pgoods_id"
            label="商品ID"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="pgoods_name" label="商品名称" align="center">
            <template slot-scope="scope">
              <span class="name" @click="chooseGoods(scope.row)">{{
                scope.row.pgoods_name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="pgoods_price"
            label="售价(元)"
            align="center"
            width="120"
          >
            <template slot-scope="scope">{{
              scope.row.pgoods_points / 100
            }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div class="tips">点击商品即可选择商品</div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchTotal"
      >
      </el-pagination>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      row: this.$route.params.row,
      list: [],
      timeList: [
        { value: "1", label: "15分钟" },
        { value: "2", label: "30分钟" },
        { value: "3", label: "1小时" },
        { value: "4", label: "2小时" },
        { value: "5", label: "4小时" },
        { value: "6", label: "8小时" },
        { value: "7", label: "24小时" },
      ],
      drawerVibile: false,
      start: "",
      end: "",
      searchObj: {
        pgoods_id: "",
        pgoods_name: "",
        pgoods_show: 1,
        page: 1,
        pageSize: 10,
      },
      searchList: [],
      searchTotal: 0,
      currentPage: 1,
      theight: 650,
      editItem: null,
      key: false,
      oHeight:0
    };
  },
  created() {
    if (this.row.status != "-1") {
      this.getInfo();
    }
  },
  mounted(){
    let h = this.$refs.tablebox.offsetHeight
    this.$nextTick(()=>{
      this.oHeight = h
    })
  },
  methods: {
    getInfo() {
      let data = { activity_id: this.row.activity_id };
      this.$http
        .get("/admin/pointprod/index.php?act=pt&op=activityDetail", {
          params: data,
        })
        .then((res) => {
          if (res.code == 1) {
            this.list = res.data.goods;
            if (!this.row.copy) {
              this.start = res.data.start_time;
              this.end = res.data.end_time;
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    addCommodity() {
      this.drawerVibile = true;
    },
    // 搜索商品
    searchGoods() {
      let data = {};
      if (this.searchObj.pgoods_id != "")
        data.pgoods_id = this.searchObj.pgoods_id;
      if (this.searchObj.pgoods_name != "")
        data.pgoods_name = this.searchObj.pgoods_name;
      data.pgoods_show = this.searchObj.pgoods_show;
      data.page = this.searchObj.page;
      data.pageSize = this.searchObj.pageSize;
      this.$http
        .get("/admin/pointprod/index.php?act=pointGoods&op=list", {
          params: data,
        })
        .then((res) => {
          if (res.code == 1) {
            this.searchList = res.data.list;
            this.searchTotal = res.data.totalCount;
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    handleSizeChange(val) {
      this.searchObj.pageSize = val;
      this.searchGoods();
    },
    handleCurrentChange(val) {
      this.searchObj.page = val;
      this.searchGoods();
    },
    chooseGoods(item) {
      let l = this.list.filter((v) => v.pgoods_id == item.pgoods_id).length;
      if (l > 0) {
        this.$message.warning("不能重复选取同一商品!");
        return;
      }    
      
      if(item.pgoods_spec == 1){
      var goodsdata = this.$http
        .post("/admin/pointprod/index.php?act=pointGoods&op=getSkuGoods", {pgoods_id:item.pgoods_id})
        .then((res) => {
          if (res.code == 1) {
            console.log(this.editItem);
            if (this.editItem == null) {//空的时候直接push
              for(var item of res.data){
                this.list.push(item);
              }
            } else {//不是空的时候先删除在push
              let checklist = [];
              for(var data of this.list){
                if(data.pgoods_id == this.editItem.pgoods_id){
                  checklist.push(data)
                }
              }
              let newchecklist = new Set(checklist);
              let minus = this.list.filter(x => !newchecklist.has(x));//两个数组的差集
              console.log(minus);
              this.list = minus;
              for(var item of res.data){
                this.list.push(item);
              }
            }      
            this.editItem = null;
            this.key = !this.key;      
          } else {
            this.$message.warning(res.msg);
            this.editItem = null;
            this.key = !this.key;
          }
        });
    }else{
      console.log(this.editItem);
      if (this.editItem == null) {
        this.list.push(item);
      } else {
        let checklist = [];
        for(var data of this.list){
          if(data.pgoods_id == this.editItem.pgoods_id){
            checklist.push(data)
          }
        }
        if(checklist.length > 1){
          // let newchecklist = new Set(checklist);
          // let minus = this.list.filter(x => !newchecklist.has(x));//两个数组的差集
          // console.log(minus);
          // this.list = minus;    
          // console.log(this.list.indexOf(checklist[0]));
          // console.log(checklist.length);
          // console.log(this.list.splice(this.list.indexOf(checklist[0]),checklist.length,item)); 
          this.list.splice(this.list.indexOf(checklist[0]),checklist.length,item) 
        }else{
          this.list[this.list.indexOf(this.editItem)] = item;
        }

      }
      this.editItem = null;
      this.key = !this.key;
    }
      // console.log(this.list)

      this.closeDrawer();

    },
    deleteGoods(item) {
      this.$confirm("确认删除该商品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let checklist = []
        for(var data of this.list){
          console.log(data.pgoods_id);
          console.log(item.pgoods_id);
           if(data.pgoods_id == item.pgoods_id){
            //  this.list.splice(this.list.indexOf(data), 1);
            checklist.push(data)
           }
        }
        // let newlist = new Set(this.list);
        let newchecklist = new Set(checklist);
        let minus = this.list.filter(x => !newchecklist.has(x));//两个数组的差集
        console.log(minus);
        this.list = minus;
        this.$message.success("删除成功!");
      });
    },
    editGoods(item) {
      this.drawerVibile = true;
      console.log(item)
      this.editItem = item;
    },
    submitCommodity() {
      if (this.list.length <= 0) {
        this.$message.warning("请选择商品");
        return;
      }
      if (this.start == "") {
        this.$message.warning("请选择开始时间");
        return;
      }
      if (this.end == "") {
        this.$message.warning("请选择结束时间");
        return;
      }
      let goods = [];
      this.list.map((v) => {
        let i = {
          pgoods_id: v.pgoods_id,
          pt_price: v.pt_price,
          minimum_people: v.minimum_people,
          expire_type: v.expire_type,
          sort: v.sort,
          goods_sku:v.sku?v.sku:v.goods_sku,
        };
        goods.push(i);
      });
      let data = {};
      if (this.row.status == "0") {
        data.activity_id = this.row.activity_id;
      }
      data.start_time = this.start;
      data.end_time = this.end;
      data.goods = goods;
      data = this.$http
        .post("/admin/pointprod/index.php?act=pt&op=savePtActivity", data)
        .then((res) => {
          if (res.code == 1) {
            this.list = [];
            this.start = "";
            this.end = "";
            this.$message.success(res.msg);
            this.$emit("addVibible", { status: "actlist" });
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    closeDrawer() {
      // this.searchObj = {
      //   pgoods_id: "",
      //   pgoods_name: "",
      //   pgoods_show: 1,
      //   page: 1,
      //   pageSize: 10,
      // };
      // this.searchList = [];
      // this.searchTotal = 0;
      // this.currentPage = 1;
      this.drawerVibile = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.add-activity {
  height: 94%;
  font-size: 14px;
  .screen {
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
    font-size: 14px;
    align-items: center;
    .screen-item {
      margin: 10px;
    }
  }
  .table-title,
  .table-item {
    display: flex;
    padding: 10px;
    > div {
      display: flex;
      justify-content: center;
      align-items: center;
      .el-input {
        width: 90%;
      }
    }
    .medium {
      width: 30%;
      .commodity-name {
        width: 100%;
        height: 100%;
        border: 1px solid #e4e7ed;
        border-radius: 5px;
        line-height: 25px;
        padding: 0 5px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .small {
      width: 10%;
    }
    .mini {
      width: 8%;
    }
    /deep/.el-input__inner {
      padding: 0 5px;
    }
  }
  .add-commodity {
    margin-left: 10px;
    margin-top: 10px;
  }
  .el-drawer {
    .commodity-search {
      display: flex;
      align-items: center;
      padding: 20px;
      .el-input {
        width: 20%;
        margin: 0 15px;
      }
    }
    .commodity-table {
      padding: 10px 20px;
      .name {
        color: #409eff;
        cursor: pointer;
        border-bottom: 1px solid #409eff;
      }
    }
    .tips {
      width: 100%;
      text-align: center;
    }
    .el-pagination {
      display: flex;
      justify-content: flex-end;
      padding-right: 25px;
    }
  }
}
.box {
  display: flex;
  flex-direction: column;
  height: 100%;
  .tablebox {
    flex: 1;
  }
  .btnbox {
    height: 40px;
    margin-top: 10px;
  }
}
</style>
